package com.heima.search.service.iml;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-05-27 12:19
 */
@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索记录
     *
     * @param keyword     关键字
     * @param userId      用户ID
     * @param equipmentId 设备ID
     */
    @Override
    @Async
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {
        //0.判断用户是否当前搜索记录
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(equipmentId));
        }
        query.addCriteria(Criteria.where("keyword").is(keyword));
        long count = mongoTemplate.count(query, ApUserSearch.class);
        //1.构建搜索记录记录对象
        if (count == 0) {
            ApUserSearch apUserSearch = new ApUserSearch();
            //2.执行保存保存（）
            apUserSearch.setKeyword(keyword);
            apUserSearch.setEquipmentId(equipmentId);
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setUserId(userId);
            mongoTemplate.save(apUserSearch);
        } else {
            //如果存在更新时间
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, ApUserSearch.class);
        }
    }

    /**
     * 查询当前登录用户搜索记录
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        //1.封装查询条件 用户ID或设备ID，排序，前五条
        Query query = new Query();
        //1.1 设置用户ID或者设备ID
        User user = UserThreadLocalUtil.get();
        if (user.getUserId() != null) {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //1.2 设置排序 根据时间倒序;分页
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.DESC, "createdTime");
        query.with(pageable);
        //2.执行查询
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        //构建删除条件
        Query query = new Query();
        if (!CollectionUtils.isEmpty(dto.getHisList())) {
            List<String> collect = dto.getHisList().stream().map(ApUserSearch::getId).collect(Collectors.toList());
            query.addCriteria(Criteria.where("id").in(collect));
        }
        //执行删除
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
